﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using PerfumeShopManagement.Utility;
using PerfumeShopManagement.DAL;
using PerfumeShopManagement.Model;
using PerfumeShopManagement.BLL;
using System.Threading;

namespace PerfumeShopManagement.View
{
    public partial class frmExportCheck : Form
    {
        private BllExportCheck bllExportCheck;
        private BllAccount bllAccount;
        private int id;

        public frmExportCheck(int id, BllExportCheck bllExportCheck, BllAccount bllAccount)
        {
            this.bllExportCheck = bllExportCheck;
            this.bllAccount = bllAccount;
            this.id = id;
            InitializeComponent();
        }

        private void doAutoDateTime()
        {
            //start the time running
            backgroundWorker.RunWorkerAsync();
        }

        public void ResetFieldWithoutId()
        {
            // Reset without id
            lblTotal.Text = "0.0";
            cbbCustomer.Text = "";
            reloadGridView();
        }

        private void setTotal()
        {
            float total = 0.0f;

            if (gridProducts.Rows.Count > 1)
            {
                for (int i = 0; i < gridProducts.Rows.Count - 1; i++)
                {
                    DataGridViewRow item = gridProducts.Rows[i];
                    try
                    {
                        int amount = int.Parse(item.Cells["colAmount"].Value.ToString());
                        float price = float.Parse(item.Cells["colPrice"].Value.ToString());
                        total += amount * price;
                    }
                    catch { } // Continue
                }
            }

            lblTotal.Text = total.ToString();
        }

        public void SetNextId()
        {
            lblExportCheckId.Text = Constants.AUTO_NUMBERING_MESSAGE;
        }

        private void reloadGridView()
        {
            // Load grid view
            object[] buffer = new object[5];
            List<DataGridViewRow> rows = new List<DataGridViewRow>();
            ExportCheck exportCheck = bllExportCheck.Get(id);
            if (exportCheck != null && exportCheck.ExportCheckDetail != null)
            {
                foreach (ExportCheckDetail item in exportCheck.ExportCheckDetail)
                {
                    buffer[0] = item.Product.ProductId;
                    buffer[1] = item.Product.ProductName;
                    buffer[2] = item.Product.Price;
                    buffer[3] = item.ExportCheckAmount;

                    rows.Add(new DataGridViewRow());
                    rows[rows.Count - 1].CreateCells(gridProducts, buffer);
                }
                gridProducts.Rows.Clear();
                gridProducts.Rows.AddRange(rows.ToArray());
            }
        }

        private void reloadCustomerList()
        {
            List<User> users = new BllAccount().GetAll();
            cbbCustomer.Items.Clear();
            foreach (User user in users)
            {
                cbbCustomer.Items.Add(user.Name);
            }
        }

        private void setId()
        {
            if (id == int.MaxValue)
            {
                lblExportCheckId.Text = Constants.AUTO_NUMBERING_MESSAGE;
            }
            else
            {
                lblExportCheckId.Text = id.ToString();
            }
        }

        private void frmExportCheck_Load(object sender, EventArgs e)
        {
            setId();
            setCustomer();
            reloadCustomerList();
            reloadGridView();
            setTotal();
            doAutoDateTime();
        }

        private void setCustomer()
        {
            ExportCheck exportCheck = bllExportCheck.Get(id);
            if (exportCheck != null)
                cbbCustomer.Text = bllExportCheck.Get(id).User.Name;
        }

        private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            while (true)
            {
                Thread.Sleep(500);
                if (lblExportDate != null)
                {
                    if (!lblExportDate.InvokeRequired)
                    {
                        DateTime now = DateTime.Now;
                        lblExportDate.Text = String.Format("{0:dd/MM/yyyy HH:mm:ss}", now);
                    }
                }
            }
        }

        private void btnSaveExportCheck_Click(object sender, EventArgs e)
        {
            // Creates ExportCheck Object for Saving
            ExportCheck exportCheck = new ExportCheck();
            if (NumberUtil.IsNumeric(lblExportCheckId.Text))
                exportCheck.ExportCheckId = int.Parse(lblExportCheckId.Text);
            exportCheck.Status = Constants.NEW_STATUS;
            exportCheck.ExportCheckTime = DateTime.Now;
            if (!StringUtil.isEmptyOrBlank(cbbCustomer.Text))
            {
                User user = new User();
                user.Name = cbbCustomer.Text;
                List<User> users = bllAccount.Search(user);
                if (users.Count > 0)
                    exportCheck.Username = users[0].Username;
            }
            if (NumberUtil.IsNumeric(lblTotal.Text))
                exportCheck.Total = double.Parse(lblTotal.Text);

            for (int i = 0; i < gridProducts.RowCount - 1; i++)
			{
                ExportCheckDetail exportCheckDetail = new ExportCheckDetail();
                
                DataGridViewRow item = gridProducts.Rows[i];
                if (NumberUtil.IsNumeric(item.Cells["colProductId"].Value))
                    exportCheckDetail.ProductId = int.Parse(item.Cells["colProductId"].Value.ToString());
                if (NumberUtil.IsNumeric(item.Cells["colAmount"].Value))
                    exportCheckDetail.ExportCheckAmount = int.Parse(item.Cells["colAmount"].Value.ToString());

                exportCheck.ExportCheckDetail.Add(exportCheckDetail);
			}

            // Executes saving
            if (bllExportCheck.Save(exportCheck))
            {
                MessageBox.Show(Constants.SUCCESSFULLY_MESSAGE);
                this.Close();
            }
            else
            {
                MessageBox.Show(Constants.FAILED_MESSAGE);
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void gridProducts_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            setTotal();
        }
    }
}
